package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private TravelCommentRepository repository;

    @Override
    public TravelComment saveOrUpdate(TravelComment detail, UserInfo userInfo) {
        if (detail == null || userInfo == null) {
            throw new LogicException("参数错误");
        }
        if (detail.getId() == null) {
            detail.setCreateTime(new Date());
        }
        detail.setHeadUrl(userInfo.getHeadImgUrl());
        detail.setCity(userInfo.getCity());
        detail.setUsername(userInfo.getNickname());
        detail.setUserId(userInfo.getId());
        detail.setLevel(userInfo.getLevel());
        if (detail.getType() == TravelComment.TRAVEL_COMMENT_TYPE) {
            String id = detail.getRefComment().getId();
            if (StringUtils.hasLength(id)) {
                detail.setRefComment(repository.findById(id).get());
            }
        }
        // 插入数据到mongodb中
        return repository.save(detail);
    }

    @Override
    public List<TravelComment> queryById(Long id) {
        if (id == null) {
            return Collections.emptyList();
        }
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.ASC, "createTime"));
        query.addCriteria(Criteria.where("travelId").is(id));
        List<TravelComment> list = template.find(query, TravelComment.class);
        return list;
    }

    @Override
    public long countFloor(Long travelId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("travelId").is(travelId));
        return  template.count(query, TravelComment.class);
    }

    @Override
    public List<TravelComment> queryByUserId(Long uid) {
        if (uid == null) {
            return Collections.emptyList();
        }
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.ASC, "createTime"));
        query.addCriteria(Criteria.where("userId").is(uid));
        List<TravelComment> list = template.find(query, TravelComment.class);
        return list;
    }
}
